<template>
  <ElCard style="width: 500px; margin: 10px auto">
    <ElForm :inline="false" :label-width="120">
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="姓名">
            {{ cardUser.partyName }}
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="性别">
            {{
              cardUser?.gender === 0 ? "女" : cardUser?.gender === 1 ? "男" : ""
            }}
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="身份证号">
            <ElInput v-model="cardUser.certNumber" style="width: 240px">
              <template #append>
                <ElButton
                  icon="Search"
                  @click="checkPersonalBySearch"
                ></ElButton>
              </template>
            </ElInput>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="体检项目">
            <ElCheckbox label="身高体重" v-model="cardForm.isHw"></ElCheckbox>
            <ElCheckbox
              label="体检血压"
              v-model="cardForm.isBlood"
            ></ElCheckbox>
            <ElCheckbox label="体检尿液" v-model="cardForm.isNiao"></ElCheckbox>
            <ElCheckbox label="体检生化" v-model="cardForm.isSh"></ElCheckbox>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="二维码打印张数">
            <ElRadioGroup v-model="cardForm.number">
              <ElRadio :label="1">1</ElRadio>
              <ElRadio :label="2">2</ElRadio>
              <ElRadio :label="3">3</ElRadio>
              <ElRadio :label="4">4</ElRadio>
              <ElRadio :label="5">5</ElRadio>
              <ElRadio :label="6">6</ElRadio>
              <ElRadio :label="7">7</ElRadio>
              <ElRadio :label="8">8</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="自动打印">
            <ElCheckbox v-model="cardForm.isAuto"></ElCheckbox>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol style="text-align: center">
          <el-button type="danger" @click="handlePrint">打印</el-button>
          <el-button type="primary" @click="handleClear">清空</el-button>
          <el-button type="warning" @click="handleAddProfiles"
            >新建档案</el-button
          >
        </ElCol>
      </ElRow>
    </ElForm>
  </ElCard>

  <MyDialog v-bind="myDialog" v-model:visible="myDialog.visible">
    <ElForm :model="cardUser" :label-width="120">
      <ElFormItem prop="partyName" label="姓名">
        <ElInput v-model="cardUser.partyName"></ElInput>
      </ElFormItem>
      <ElFormItem prop="partyName" label="身份证号">
        <ElInput v-model="cardUser.certNumber"></ElInput>
      </ElFormItem>
      <ElFormItem prop="partyName" label="性别">
        <ElRadioGroup v-model="cardUser.gender">
          <ElRadio :label="0">女</ElRadio>
          <ElRadio :label="1">男</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem prop="partyName" label="详细地址">
        <ElInput v-model="cardUser.certAddress"></ElInput>
      </ElFormItem>
    </ElForm>
  </MyDialog>
</template>

<script setup lang="ts">
/**
 * 整体逻辑  ws推送身份证数据，收到推送事件，直接查档案是否存在，如果档案存在，判断是否自动打印，如果自动打印，条用打印
 *                                                                                如果不自动打印，点击打印按钮，调用打印逻辑
 *                                                     如果档案不存在，提示通过姓名，身份证号，地址，性别快速创建个人档案，
 *          手动输入身份证号，点击查询，如果存在个人档案，
 *                                 如果不存在个人档案，提示档案不存在，
 * 新增个人档案按钮  通过姓名，身份证号，地址，性别快速创建个人档案
 *
 *
 * 问题：登录页面打开的话存在两个监听，会有逻辑问题
 */
import { ipcRenderer } from "electron";
import { getCurrentInstance, inject, ref } from "vue";
import {
  getProfilesInfoByCardId,
  saveProfiles,
  saveQrCode,
  searchProfilesByNoId,
} from "@/api/archives";
import { ElMessage, ElMessageBox } from "element-plus";
import { ICardReaderContent } from "@/model/ICardReader";
import useMyDialog from "@/components/MyDialog/useMyDialog";
import { IA00_03 } from "@/model";
import { useWs } from "@/utils/SingleWS";

/**
 * 个人档案记录，必须有个人档案才让打印
 */
const profiles = ref<Partial<IA00_03>>({});
// 扫码或填写给出的值
const cardUser = ref<Partial<ICardReaderContent>>({});

// 扫码成功的回调
const handleCardReaderSuccess = async (data) => {
  cardUser.value.partyName = data.resultContent.partyName;
  cardUser.value.gender = data.resultContent.gender;
  cardUser.value.certNumber = data.resultContent.certNumber;
  cardUser.value.certAddress = data.resultContent.certAddress;
  // TODO:1判断是否存在档案，如果不存在，弹出新增提示框
  try {
    const checkResult = await checkPersonal();
    if (checkResult === true) {
      if (cardForm.value.isAuto) handlePrint();
    }
  } catch (error) {
    cardUser.value = {};
    profiles.value = {};
  }
};
useWs(handleCardReaderSuccess);

const handleClear = () => {
  cardUser.value = {};
  profiles.value = {};
};
const cardForm = ref<{
  number?: number;
  isHw?: boolean;
  isNiao?: boolean;
  isBlood?: boolean;
  isSh?: boolean;
  isAuto?: boolean;
}>({
  number: 4,
});

const checkPersonal = () => {
  return new Promise(async (resolve, reject) => {
    const flag: any = await searchProfilesByNoId(cardUser.value.certNumber);
    if (flag.exist) {
      profiles.value = await getProfilesInfoByCardId(cardUser.value.certNumber);
      resolve(true);
    } else {
      // 创建个人档案
      ElMessageBox.confirm(
        `<div>
          <div>姓名：${cardUser.value?.partyName}</div>
          <div>性别：${cardUser.value?.gender === 1 ? "男" : "女"}</div>
          <div>身份证号：${cardUser.value?.certNumber}</div>
          <div>详细住址：${cardUser.value?.certAddress}</div>
          </div>`,
        "用户不存在，是否添加?",
        {
          dangerouslyUseHTMLString: true,
        }
      )
        .then(async () => {
          try {
            profiles.value = (await saveProfiles({
              a00_03_10: cardUser.value?.certNumber,
              a00_03_05: cardUser.value?.partyName,
              a00_03_07: cardUser.value?.gender === 1 ? "1" : "2",
              full_address: cardUser.value.certAddress,
            })) as IA00_03;
            resolve(true);
          } catch (e) {
            reject("创建个人档案失败");
          }
        })
        .catch(() => {
          reject(false);
          profiles.value = {};
        });
    }
  });
};

const handlePrint = async () => {
  if (profiles.value?.a00_03_10) {
    // TODO:校验是否存在个人档案，
    try {
      if (!cardForm.value.number) {
        return ElMessage.error("请先选择二维码打印张数");
      }
      const result: any = await saveQrCode({
        id_no: cardUser.value.certNumber,
      });
      console.log(result, 'result')
      const lgtText = ref('');
      if (result.age >= 65) {
        lgtText.value += '老';
      }
      if (profiles.value.gao == '是') {
        lgtText.value += '高';
      }
      if (profiles.value.tang == '是') {
        lgtText.value += '糖';
      }
      const printData = {
        id: result?.id + "",
        username: cardUser.value.partyName,
        sex: cardUser.value?.gender === 0 ? "女" : "男",
        idno: cardUser.value.certNumber,
        age: result.age,
        lgt: lgtText.value, // 老高糖
      };

      ipcRenderer.send("print-qr-code", {
        printData: printData,
        copies: cardForm.value.number,
      });
      cardUser.value = {};
    } catch (e) {
      ElMessage.error("生成二维码失败");
    }
    // 创建二维码
  } else {
    ElMessage.error("没有个人档案，不能打印");
  }
};

const myDialog = useMyDialog({
  title: "新增个人档案",
  visible: false,
  handleConfirmClick: async () => {
    profiles.value = (await saveProfiles({
      a00_03_10: cardUser.value?.certNumber,
      a00_03_05: cardUser.value?.partyName,
      a00_03_07: cardUser.value?.gender === 0 ? "2" : "1",
      full_address: cardUser.value.certAddress,
    })) as IA00_03;
    if (cardForm.value.isAuto) {
      handlePrint();
    }
    return Promise.resolve(true);
  },
});

const handleAddProfiles = () => {
  myDialog.visible = true;
};
const checkPersonalBySearch = async () => {
  if (!cardUser.value.certNumber) return;
  try {
    const result: any = await getProfilesInfoByCardId(
      cardUser.value.certNumber
    );
    if (result) {
      cardUser.value = {
        certNumber: result.a00_03_10,
        partyName: result.a00_03_05,
        gender: result.a00_03_07 === "1" ? 1 : 0,
      };
      profiles.value = result;
      if (cardForm.value.isAuto) {
        handlePrint();
      }
    }
  } catch (error) {
    console.log(error);
  }
};
</script>

<style scoped lang="scss"></style>
